# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:views.py
@time:2020/09/08
"""
from django.db.models import Q
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.views import APIView
from apps.system.models import Option
from apps.system.serializers import OptionDictSerializer
from apps.product.models import Product
from utils import response_ok
from .serializers import ProductAppSeializer, ProductDetailAppSeializer, CategoryProductSerializer
from .filters import ProductAppFilter


class ProductDictView(APIView):
    def get(self, request):
        ret = {
            'category': OptionDictSerializer(Option.objects.filter(type=Option.PRODUCT_CATEGORY, enable=True),
                                             many=True).data
        }
        return response_ok(ret)


# 小程序产品分类页数据
class CategoryProductsListView(APIView):
    def get(self, request):
        ret = CategoryProductSerializer(Option.objects.filter(type=Option.PRODUCT_CATEGORY, enable=True),
                                        many=True)
        return response_ok(ret.data)


class ProductListView(generics.ListAPIView):
    queryset = Product.objects.filter(delete=False, status=Product.SHELVE)
    serializer_class = ProductAppSeializer

    def filter_queryset(self, queryset):
        f = ProductAppFilter(self.request.GET, queryset=queryset)
        return f.qs


class ProductHotandRecommendListView(generics.ListAPIView):
    # 热门推荐
    queryset = Product.objects.filter(delete=False, status=Product.SHELVE)
    serializer_class = ProductAppSeializer

    def filter_queryset(self, queryset):
        queryset = queryset.filter(Q(is_hot=True) | Q(is_recommend=True))
        f = ProductAppFilter(self.request.GET, queryset=queryset)
        return f.qs


class ProductDetailView(generics.RetrieveAPIView):
    queryset = Product.objects.filter(delete=False, status=Product.SHELVE)
    serializer_class = ProductDetailAppSeializer


class ProductDetaiDetailslView(APIView):
    # 单独获取产品详情，解决加载慢的问题
    def get(self, request, pk):
        product = Product.get_instance_by_id(pk)
        return response_ok(product.details)
